<script setup lang="ts">
import {
  getLibraryList, //dellibrary, exportLog
  exportLog,
} from "@/api/ActionLog/index";
import type { LibraryPageVo, RequestParams } from "@/api/ActionLog/types";
import dayjs from "dayjs";
import { ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
const hasRole = (role: any) => {
  return useStore.user.roles.includes(role);
};
const libraryList = ref([] as LibraryPageVo[]); //列表数据
//const queryFormRef = ref(); //refForm
const ids = ref([]); //表格全选
const total = ref();
const loading = ref(false);
const dateRange = ref([] as any);
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
} as RequestParams);
/**
 * 列表数据
 */

const getList = async () => {
  try {
    (queryParams.value.beginDate = dateRange.value[0]),
      (queryParams.value.endDate = dateRange.value[1]);

    const res = await getLibraryList(queryParams.value);
    const updatedRobotStatusList = res.data.records.map((record: any) => {
      const timestamp = record.operTime; // 假设时间戳单位为秒
      const date = dayjs(timestamp);
      const formattedDate = date.format("YYYY/MM/DD HH:mm:ss"); // 使用 dayjs.format 方法转换为指定的日期时间格式

      record.operTime = formattedDate;

      return record;
    });
    libraryList.value = updatedRobotStatusList;
    total.value = res.data.total;
   // console.log(res.data, "系统日志分页列表");
    // console.log(queryParams.value);
  } catch (error) {
    console.error(error);
  }
};
/**
 * 重置
 */
// const resetQuery = () => {
//   queryFormRef.value.resetFields();
//   queryParams.value = {} as any;
//   dateRange.value = [];
//   queryParams.value.pageNum = 1;
//   queryParams.value.pageSize = 10;
//   getList();
// };
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// const formatDateTime = () => {
//   const [beginDate, endDate] = dateRange.value;
//   dateRange.value = [
//     dayjs(beginDate).format("YYYY-MM-DD HH:mm:ss"),
//     dayjs(endDate).format("YYYY-MM-DD HH:mm:ss"),
//   ];
// };

// const formatDateTime = () => {
//   const formattedDateTime = dayjs(queryParams.value.beginDate).format(
//     "YYYY-MM-DD HH:mm:ss"
//   );
//   const formattedDate = dayjs(queryParams.value.endDate).format(
//     "YYYY-MM-DD HH:mm:ss"
//   );
//   queryParams.value.beginDate = formattedDateTime;
//   queryParams.value.endDate = formattedDate;
// };
// const shortcuts = [
//   {
//     text: "上周",
//     value: () => {
//       const end = new Date();
//       const start = new Date();
//       start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
//       return [start, end];
//     },
//   },
//   {
//     text: "上个月",
//     value: () => {
//       const end = new Date();
//       const start = new Date();
//       start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
//       return [start, end];
//     },
//   },
//   {
//     text: "三个月前",
//     value: () => {
//       const end = new Date();
//       const start = new Date();
//       start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
//       return [start, end];
//     },
//   },
// ];
/**
 * 删除
 */
// const dell = (row: any) => {
//   const userIds = [row.id || ids.value].join(",");
//   if (!userIds) {
//     ElMessage.warning("请勾选删除项");
//     return;
//   }
//   ElMessageBox.confirm("确认删除吗?", "警告", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//   }).then(async function () {
//     const res = await dellibrary(userIds);
//     if (res.code === 200) {
//       getList();
//       setTimeout(() => {
//         getList();
//       }, 1000);
//       ElMessage.success("删除成功");
//     }
//   });
// };
/**
 * 枚举
 */
const getStatus = (status: number) => {
  const STATUSES = [
    { id: 1, name: "失败" },
    { id: 0, name: "成功" },
  ];
  const matched = STATUSES.find((item) => item.id === status);
  return matched ? matched.name : "";
};
/**
 * 导出用户
 */
function handleUserExport() {
  ElMessageBox.confirm("确认导出操作日志吗？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      exportLog(queryParams.value).then((response: any) => {
        const blob = new Blob([response.data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
        });
        const a = document.createElement("a");
        const href = window.URL.createObjectURL(blob); // 下载的链接
        a.href = href;
        // a.download = decodeURI(
        //   response.headers["content-disposition"].split(";")[1].split("=")[1]
        // ); // 获取后台设置的文件名称
        a.download = "operationLog";
        document.body.appendChild(a);
        a.click(); // 点击导出
        document.body.removeChild(a); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "Delete canceled",
      // });
    });
}
onMounted(() => {
  getList();
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
</script>

<template>
  <div class="app-container">
    <!-- <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="操作人员">
          <el-input
            style="width: 190px"
            v-model="queryParams.operName"
            placeholder="请输入操作人员"
          />
        </el-form-item>
        <el-form-item label="操作名称">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入操作名称"
            style="width: 190px"
          />
        </el-form-item>
        <el-form-item label="日期查询">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            @change="formatDateTime"
            :shortcuts="shortcuts"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
    <el-card>
      <template #header>
        <el-button
          type="success"
          v-if="hasRole('ADMIN') || hasRole('LIBRARY_ROOT')"
          @click="handleUserExport"
          >excel导出</el-button
        >
        <!-- <el-button
          v-hasPerm="['sys.ActionLog.Alldelete']"
          type="danger"
          :disabled="ids.length === 0"
          @click="dell"
          ><i-ep-delete />删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="libraryList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <el-table-column label="操作人员" prop="operName" :align="'center'" />
        <el-table-column label="操作名称" prop="title" :align="'center'" />
        <el-table-column
          label="操作时间"
          prop="operTime"
          :align="'center'"
          width="200"
        />
        <el-table-column
          label="主机地址"
          prop="operIp"
          :align="'center'"
          width="200"
        />
        <el-table-column
          label="业务类型"
          prop="businessType"
          :align="'center'"
        />

        <el-table-column
          label="请求方式"
          prop="requestMethod"
          :align="'center'"
        />
        <el-table-column label="登录状态" prop="status" :align="'center'">
          <template #default="{ row }">
            {{ getStatus(row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="错误消息" prop="errorMsg" :align="'center'" />

        <!-- <el-table-column
          fixed="right"
          label="操作"
          :align="'center'"
          width="220"
        >
          <template #default="{ row }">
            <el-button
              v-hasPerm="['sys.ActionLog.delete']"
              type="primary"
              link
              size="small"
              @click="dell(row)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
* {
  list-style: none;
}

el-select {
  padding-bottom: 100px;
}
</style>
exportLog, import { ElMessageBox } from "element-plus";
